package com.huike.web.controller.report;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import com.huike.clues.domain.vo.cluesStatisticsVo;
import com.huike.common.core.domain.entity.BCStatisticsVo;
import com.huike.common.core.domain.entity.SJStatisticsVo;
import com.huike.common.core.domain.model.splitMonths;
import com.huike.report.domain.vo.LineChartVO;
import com.huike.report.domain.vo.LineSeriesVO;
import com.huike.report.domain.vo.VulnerabilityMapVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.huike.clues.domain.TbActivity;
import com.huike.clues.domain.TbClue;
import com.huike.common.core.controller.BaseController;
import com.huike.common.core.domain.AjaxResult;
import com.huike.common.core.page.TableDataInfo;
import com.huike.contract.domain.TbContract;
import com.huike.report.domain.vo.ActivityStatisticsVo;
import com.huike.report.service.IReportService;


@RestController
@RequestMapping("/report")
public class ReportController extends BaseController {

    @Autowired
    private IReportService reportService;


    /**
     * 客户统计
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @GetMapping("/contractStatistics/{beginCreateTime}/{endCreateTime}")
    public LineChartVO contractStatistics(@PathVariable String beginCreateTime, @PathVariable String endCreateTime) {
        return reportService.contractStatistics(beginCreateTime, endCreateTime);
    }

    /**
     * 销售统计
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @GetMapping("/salesStatistics/{beginCreateTime}/{endCreateTime}")
    public LineChartVO salesStatistics(@PathVariable String beginCreateTime, @PathVariable String endCreateTime) {
        return reportService.salesStatistics(beginCreateTime, endCreateTime);
    }


    /**
     * 渠道统计
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @GetMapping("/chanelStatistics/{beginCreateTime}/{endCreateTime}")
    public AjaxResult chanelStatistics(@PathVariable String beginCreateTime, @PathVariable String endCreateTime) {
        return AjaxResult.success(reportService.chanelStatistics(beginCreateTime, endCreateTime));
    }


    /**
     * 活动统计
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @GetMapping("/activityStatistics/{beginCreateTime}/{endCreateTime}")
    public AjaxResult activityStatistics(@PathVariable String beginCreateTime, @PathVariable String endCreateTime) {
        return AjaxResult.success(reportService.activityStatistics(beginCreateTime, endCreateTime));
    }

    /**
     * 查询活动管理列表
     */
    @GetMapping("/contractStatisticsList")
    public TableDataInfo contractStatisticsList(TbContract contract) {
        startPage();
        List<TbContract> list = reportService.contractReportList(contract);
        return getDataTable(list);
    }


    /**
     * 销售统计部门报表
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @GetMapping("/deptStatisticsList/{beginCreateTime}/{endCreateTime}")
    public TableDataInfo deptStatisticsList(@PathVariable String beginCreateTime, @PathVariable String endCreateTime) {
        startPage();
        List<Map<String, Object>> list = reportService.deptStatisticsList(beginCreateTime, endCreateTime);
        return getDataTablePage(list);
    }

    /**
     * 销售统计渠道报表
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @GetMapping("/channelStatisticsList/{beginCreateTime}/{endCreateTime}")
    public TableDataInfo channelStatisticsList(@PathVariable String beginCreateTime, @PathVariable String endCreateTime) {
        startPage();
        List<Map<String, Object>> list = reportService.channelStatisticsList(beginCreateTime, endCreateTime);
        return getDataTablePage(list);
    }

    /**
     * 销售统计归属人报表
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @GetMapping("/ownerShipStatisticsList/{beginCreateTime}/{endCreateTime}")
    public TableDataInfo ownerShipStatisticsList(@PathVariable String beginCreateTime, @PathVariable String endCreateTime) {
        startPage();
        List<Map<String, Object>> list = reportService.ownerShipStatisticsList(beginCreateTime, endCreateTime);
        return getDataTablePage(list);
    }


    /**
     * 线索统计报表
     *
     * @param clue
     * @return
     */
    @GetMapping("/cluesStatisticsList")
    public TableDataInfo cluesStatisticsList(TbClue clue) {
        startPage();
        List<TbClue> list = reportService.cluesStatisticsList(clue);
        return getDataTable(list);
    }

    /**
     * 活动渠道统计
     *
     * @param activity
     * @return
     */
    @GetMapping("/activityStatisticsList")
    public TableDataInfo activityStatisticsList(TbActivity activity) {
        List<ActivityStatisticsVo> list = reportService.activityStatisticsList(activity);
        return getDataTablePage(list);
    }

    /**
     * 线索转化率漏斗图
     */
    @GetMapping("/getVulnerabilityMap/{beginCreateTime}/{endCreateTime}")
    public AjaxResult getVulnerabilityMap(@PathVariable String beginCreateTime, @PathVariable String endCreateTime) {
        //前端获取开始和结束时间，需要返回这个时间段的线索数量、有效线索数、商机数量、合同数量
        //该功能只有管理才有权限查看，获取的是所有的数据

        //线索数量,不用考虑状态有多少线索全部统计,获取指定时间段的所有线索的数量，从tb_clue表中获取数据
        CompletableFuture<Integer> cluesNums = CompletableFuture.supplyAsync(() -> reportService.getCluesNums(beginCreateTime, endCreateTime));

        //有效线索，待跟进、跟进中、转换成商机、转换成客户这个状态的枚举类在TbClue中
        CompletableFuture<Integer> effectiveCluesNums = CompletableFuture.supplyAsync(() -> reportService.getEffectiveCluesNums(beginCreateTime, endCreateTime));

        //商机数量，线索转换成商机的需要考虑状态是：待跟进， 根进中,转换成客户
        CompletableFuture<Integer> businessNums = CompletableFuture.supplyAsync(() -> reportService.getBusinessNums(beginCreateTime, endCreateTime));

        //合同数量，转换成合同的不用考虑状态，只要是合同统计但是结果集是要从转换成商机中的结果中取
        CompletableFuture<Integer> contractNums = CompletableFuture.supplyAsync(() -> reportService.getContractNums(beginCreateTime, endCreateTime));

        CompletableFuture.allOf(cluesNums, effectiveCluesNums, businessNums, contractNums).join();

        VulnerabilityMapVo mapVo = null;
        try {
            mapVo = new VulnerabilityMapVo();
            mapVo.setCluesNums(cluesNums.get());
            mapVo.setEffectiveCluesNums(effectiveCluesNums.get());
            mapVo.setBusinessNums(businessNums.get());
            mapVo.setContractNums(contractNums.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(mapVo);
    }

    /**
     * 统计分析-客户统计-学科客户分布饼图
     */
    @GetMapping("/subjectStatistics/{beginCreateTime}/{endCreateTime}")
    public AjaxResult subjectStatistics(@PathVariable String beginCreateTime, @PathVariable String endCreateTime) {
        //统计在时间段内每个学科的报名情况，和占比，用来分析出每个学科的火热程度
        //在合同表中按照学科分组，统计学科的人数，然后通过课程id找到对应的名字
        List<SJStatisticsVo> list = reportService.getSubjectStatistics(beginCreateTime, endCreateTime);

        return AjaxResult.success(list);
    }

    /**
     * 统计分析--线索统计--新增线索数量折线图
     */
    @GetMapping("/cluesStatistics/{beginCreateTime}/{endCreateTime}")
    public LineChartVO cluesStatistics(@PathVariable String beginCreateTime, @PathVariable String endCreateTime) {
        Date begin =null;
        Date end =null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            begin = dateFormat.parse(beginCreateTime);
            end = dateFormat.parse(endCreateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //获取给定时间内的所有的日期
        ArrayList<String> list = splitMonths.getDateInterval(begin, end);

        //统计出一段时间内的每一天 新增的线索数量
        //通过每天新增的线索数量和线索总数量，分析线上线下活动的执行情况
        //[cluesStatisticsVo(date=2023-03-28, num=1), cluesStatisticsVo(date=2023-03-31, num=3)
        // cluesStatisticsVo(date=2023-04-01, num=5), cluesStatisticsVo(date=2023-04-02, num=2)]
        List<cluesStatisticsVo> xAnds = reportService.cluesStatistics(beginCreateTime, endCreateTime);


        LineChartVO vo = new LineChartVO();
        List<LineSeriesVO> series = vo.getSeries();

        //新增线索
        LineSeriesVO lineSeriesVoNew = new LineSeriesVO();
        lineSeriesVoNew.setName("新增线索数量");
        Integer[] countNew=new Integer[list.size()];
        List<Object> dataNew = lineSeriesVoNew.getData();

        //遍历日期集合["2023-03-28","2023-03-29","2023-03-30",...]
        //如果日期和时间相等，就将数据放入新增线索数量集合中
        //将对应的数据存入对应位置的数组中
        for (int i = 0; i < xAnds.size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if (xAnds.get(i).getDate().equals(list.get(j))) {
                    countNew[j]=xAnds.get(i).getNum();
                }
            }
        }

        //将数组内的数据赋值给新增线索的集合
        //如果数组有元素就放入数组元素，没有元素就放入0
        for (int i = 0; i < countNew.length; i++) {
            if (countNew[i]==null) {
                dataNew.add(0);
            }else {
                dataNew.add(countNew[i]);
            }
        }

        //这段时间每一天的线索总数量
        List<cluesStatisticsVo> nums = reportService.cluesStatisticsAll(beginCreateTime, endCreateTime);
        System.out.println("num=======================================");
        for (cluesStatisticsVo num : nums) {
            System.out.println(num);
        }

        //线索总数量
        LineSeriesVO lineSeriesVoAll = new LineSeriesVO();
        lineSeriesVoAll.setName("线索总数量");
        Integer[] countAll=new Integer[list.size()];
        List<Object> dataAll = lineSeriesVoAll.getData();


        for (int i = 0; i < nums.size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if(nums.get(i).getDate().equals(list.get(j))){
                    countAll[j]=nums.get(i).getNum();
                    System.out.println("countAll[" + j + "]" + countAll[j]);
                }
            }
        }
        System.out.println("countAll==================================");
        for (Integer integer : countAll) {
            System.out.println(integer);
        }

        //null 1 null null 4 9 11 11  => 0 1 1 1 4 9 11 11
        //遍历存有数据的list集合
        for (int i = 0; i < countAll.length; i++) {
            //如果list集合数据为null，从当前位置开始向左找到不为null的数据
            //并将数据赋值给新数组
            //如果没有发现不为null的数据，就说明是第一位，赋值为0
            //不为null就给新数组赋值为当前数据
            if (countAll[i] == null) {
                Boolean flag = false;
                for (int j = i; j >=0; j--) {
                    if (countAll[j] != null) {
                        dataAll.add(countAll[j]);
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    dataAll.add(0);
                }
            } else {
                dataAll.add(countAll[i]);
            }
        }
        System.out.println("xiugaihou=================================");
        for (Object o : dataAll) {
            System.out.println(o);
        }

        series.add(lineSeriesVoNew);
        series.add(lineSeriesVoAll);
        vo.setxAxis(list);
        vo.setSeries(series);
        return vo;
    }
}
